module.exports = class extends think.Controller {
	constructor(ctx) {
		super(ctx);
		this.links = this.appModel("links", "dwz");
		this.linkssetup = this.appModel("setup", "dwz");
		

	}

	async indexAction() {
		let keyword = this.get("keyword");
		console.log(keyword);

		let link = await this.links.where({
			keyword: keyword
		}).find();
		if(think.isEmpty(link)) {
			return this.ctx.throw(404);
		}
		await this.links.setOne(link.id,{
			clicks: link.clicks+1
		});

		return this.redirect(link.url);

	}

	async shortAction() {
		try{

		let gets = this.get();
		if(think.isEmpty(gets.appid)) {
			return this.fail("appid不能为空")

		}
		if(think.isEmpty(gets.appkey)) {
			return this.fail("appkey不能为空");

		}
		let linksapp = await this.linkssetup.where({
			appid: gets.appid,
			appkey: gets.appkey
		}).find();
		if(think.isEmpty(linksapp)) {
			return this.fail("appid或appkey错误");
		}

		if(linksapp.expire_time < new Date().valueOf()) {
			return this.fail("权限已过期");
		}

		let url = gets.url;

		let test = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(url);

		if(!test) {
			return this.fail("网址不合法");

		}

		let link = await this.links.where({
			url: encodeURI(url)
		}).find();
		let keyword = link.keyword;
		if(think.isEmpty(link)) {
			let linkId = await this.links.add({
				url: encodeURI(url),
				create_time: new Date().valueOf()

			});
			keyword = think.toHex(linkId);
			await this.links.where({
				id: linkId
			}).update({
				keyword: keyword
			});

		}
		
		await this.linkssetup.setOne(linksapp.id,{
			times: linksapp.times+1
		});

		return this.success(keyword);
		}catch(e){
			console.log(e)
		}

	}


};